const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const {config} = require('../config')

// 密码加密
const encrypted = (password) => {
  return bcrypt.hashSync(password, 10);
};
// 校验密码
const verifyPwd = (password, hash) => {
  /*
    password: 需要校验的密码
    hash: 数据库中已加密的密码
  */
  return bcrypt.compareSync(password, hash);
};
// 生成token
const createToken = (userInfo, timeout = "5h") => {
  /*
    id:用户id,
    timeout:token过期时间
  */
  const token_info = {
    ...userInfo,
    ctime: new Date().getTime(), //token创建时间戳
  };
 
  const token = jwt.sign(token_info, config.token_key, { expiresIn: timeout }); // 生成token
  return token;
};

// 校验token
const varifyToken = async old_token => {
    try {
      const userInfo = await jwt.verify(old_token, config.token_key)
        let id = userInfo.r_id
      return id
    } catch (err) {
      // token已过期
      // return (console.log('varifyToken >>> ' + err))
      return false
    }
  }
  //路由白名单
const whitelist = [
    '/common/upload',
    '/updateInfo',
    '/userInfo',
    '/deleteUser',
    '/get_shop'
  ]
module.exports = {
  encrypted,
  verifyPwd,
  createToken,
  varifyToken,
  whitelist
};
